package servlet;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public abstract class BaseServlet extends HttpServlet {
	
	/*
	 * 1. 原则：处理用户请求，并响应数据给用户
	 * 2. 响应结果：转发；重定向；Ajax响应
	 * 3. 请求入口：前端控制器
	 * 4. 处理用户请求，具体执行者，业务控制器
	 * 
	 * (non-Javadoc)
	 * @see javax.servlet.GenericServlet#init()
	 */

	public static String PROJECT_REDIRECT;
	public static String PROJECT_FORWARD;
	
	@Override
	public void init() throws ServletException {
		PROJECT_REDIRECT = "r:" + getServletContext().getContextPath(); // 响应的路径: r:/项目名
		PROJECT_FORWARD = "f:";
	}
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8"); // 解决业务控制器编码 
		
		String methodName = request.getParameter("method"); // 请求接口类型
		Class clazz = this.getClass(); // 反射类，作用执行子类的方法
		try {
			if(methodName == null) {
				return; // 如果请求接口类型不存在，则终止程序
			}
			Method method = clazz.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
			
			String path = (String) method.invoke(this, request, response);
			
			// 判断path是转发；还是重定向；还是Ajax
			if(path == null) { // Ajax
				return;
			}
			
			if("r:".equals(path.substring(0, 2))) { // 重定向
				response.sendRedirect(path.substring(2));
			} else if("f:".equals(path.substring(0, 2))) { // 转发
				request.getRequestDispatcher(path.substring(2)).forward(request, response);
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
}
